<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表区域 -->
    <el-card>
      <el-button type="primary" style="margin-bottom:20px">添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <!-- 展开start -->
        <el-table-column label="展开" type="expand">
          <template v-slot='{row}'>
            <!-- 一级 -->
            <el-row v-for="item1 in row.children" :key="item1.id"
              style="border-top: 1px solid #eee;padding:20px;margin:20px">
              <el-col :span="4">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <!-- 二级 -->
                <el-row v-for="item2 in item1.children" :key="item2.id">
                  <el-col :span="4">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="20">
                    <!-- 三级 -->
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable
                      @close='removeRightById(row,item3.id)'>{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 展开end -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 操作按钮 -->
        <el-table-column label="操作">
          <template v-slot='{row}'>
            <!-- 修改 -->
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <!-- 分配角色 -->
            <el-button type="warning" size="mini" icon="el-icon-setting" @click='showSetRight(row)'>分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%">
      <el-tree :data="rightsList" :props="treeprops" show-checkbox default-expand-all node-key="id"
        :default-checked-keys="checkArr" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表数据
      rolesList: [],
      // 是否显示分配权限对话框
      setRightDialogVisible: false,
      // 树状权限数据
      rightsList: [],
      // 树形控件属性绑定对象
      treeprops: {
        label: 'authName',
        children: 'children'
      },
      // 存放三级权限的id
      checkArr: [],
      // 角色的id
      rolesId: ''
    }
  },
  methods: {
    // 点击分配权限对话框确定按钮分配权限
    async allotRight () {
      const keys = [
        // 全选
        ...this.$refs.treeRef.getCheckedKeys(),
        // 半选
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const Str = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: Str })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('更新成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 点击分配权限按钮显示分配权限对话框
    async showSetRight (row) {
      this.rolesId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.rightsList = res.data
      // 获取三级权限的id
      const arr = []
      row.children.forEach(item1 => {
        if (item1.children && item1.children.length > 0) {
          item1.children.forEach(item2 => {
            if (item2.children && item2.children.length > 0) {
              item2.children.forEach(item3 => {
                arr.push(item3.id)
              })
            }
          })
        }
      })
      this.checkArr = arr
      // 思路二 递归
      // const arr = []
      // function fn (obj) {
      //   if (obj.children && obj.children.length > 0) {
      //     obj.children.forEach(item => {
      //       fn(item)
      //     })
      //   } else { // 退出条件
      //     arr.push(obj.id)
      //   }
      // }
      // fn(row)
      this.setRightDialogVisible = true
    },
    // 获取角色列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 删除第三级权限
    removeRightById (row, id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
        row.children = res.data
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getRolesList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 20px;
}
</style>
